#ifndef REDISMANAGER_H_
#define REDISMANAGER_H_
/*
	@date:2018/1/29
	@company:海通证券
	@func:redis管理类
	@name:cxw
*/

#include "hiredis/hiredis.h"
#include <string>
#include <map>
#include <list>
#include <vector>
#include <iostream>
#include <sstream>

class CRedisManager
{
public:
	CRedisManager(void);
	~CRedisManager(void);
	//连接redis
	bool Connect();
	void Close();

	//设置key-value
	void Set(const std::string &strKey, const std::string &strValue);
	//获取value
	std::string Get(const std::string &strKey);
	//hash表设置key-value
	void SetHashKeyValue(const std::string &strTableName, std::map<std::string, std::string> &mapKeyValueLists);
	//hash表设置key-value
	void SetHashKeyValueOrder(const std::string &strTableName, std::list<std::string> &strKeyLists, std::list<std::string> &strValueLists);

	//hash表设置key-value(二进制数据)
	void SetHashKeyValueBinary(const std::string & strTableName, std::vector<std::string> & vstrKeys, std::vector<void *>& vpValues, std::vector<int> & vpValuesLen);

	//获取hash表内的所有数据（二进制数据）
	void GetHashAllDataBinary(std::vector<std::string> &vstrKeys, std::vector<void *> &vpValues, const std::string & strTableName);

	//设置指定key的过期时间（单位：天)
	void SetKeyExpireTime(const std::string & strKey);

	//判定hash表内的key中指定子段是否存在
	bool IsExistsKey(const std::string & strKey);

	//确认连接是否存在
	bool Ping();
public:
	void SetIpAndPort(const std::string &strIp, const int &iPort, const int &iSecond = 1);
	void SetTimeOut(const int & iSecond = 1);
	void SetExpireTime(int iExpireTime);

private:
	template <class Type>
	std::string Value2String(Type t)
	{
		std::ostringstream stream;
		stream<<t;

		return stream.str();
	}

private:
	redisContext* m_redisConnect;		//连接redis
	redisReply* m_redisReply;				//操作redis

	//地址，端口号，超时时间
	std::string m_strIp;
	int m_iPort;
	int m_iSecond;

	int m_iExpireTime;		//过期时间
};

inline void CRedisManager::SetIpAndPort(const std::string & strIp, const int & iPort, const int &iSecond )
{
	m_strIp = strIp;
	m_iPort = iPort;
	m_iSecond = iSecond;
}

inline void CRedisManager::SetTimeOut(const int & iSecond)
{
	m_iSecond = iSecond;
}

inline void CRedisManager::SetExpireTime(int iExpireTime )
{
	iExpireTime = iExpireTime > 1000 ? 1000 : iExpireTime;

	m_iExpireTime = iExpireTime * 60 * 60 * 24;
}

#endif // REDISMANAGER_H_
